#include "head.h"

Stack *segPath(char *path)
{
    char *seg = strtok(path, "/");
    Stack *pathStack = createStack();
    stackPush(pathStack, seg);
    while ((seg = strtok(NULL, "/")) != NULL)
    {
        stackPush(pathStack, seg);
    }
    return pathStack;
}

/*测试
void prin(Stack *path)
{
    node_t *pNode = path->front;
    while (pNode != NULL)
    {
        printf("%s/", pNode->data);
        pNode = pNode->next;
    }
    printf("\n");
}
*/

int cdCmd(char *toPath, char *nowPath)
{
    /*测试
    char tmp[4096] = {0};
    sprintf(tmp, "%s/%s", nowPath, toPath);
    printf("%s\n", tmp);
    DIR *pdir = opendir(toPath);
    if (pdir == NULL)
    {
        printf("not exist the dir.\n");
        return -1;
    }
    */
    char tmp[4096] = {0};
    sprintf(tmp, "%s/%s", nowPath, toPath);
    DIR *pdir = opendir(tmp);
    if (pdir == NULL)
    {
        printf("not exist the dir.\n");
        return -1;
    }
    // printf("tmp = %s\n", tmp);

    char path[1024] = {0};
    Stack *segedToPath = segPath(toPath);
    Stack *segedNowPath = segPath(nowPath);

    if (strcmp(segedToPath->front->data, ".") == 0)
    {
        stackPop(segedNowPath);
    }
    else if (strcmp(segedToPath->front->data, "..") == 0)
    {
        stackPop(segedToPath);
        node_t *pNode = segedNowPath->front;
        while (pNode->next != segedNowPath->rear)
        {
            pNode = pNode->next;
        } // pNode位于rear前一位置
        pNode->next = NULL;
        free(pNode->next);
        segedNowPath->rear = pNode;
        segedNowPath->size--;
        if (segedNowPath->size < 0)
        {
            printf("Now is root dir.\n");
            return -1;
        }
    }

    if ((segedToPath->size != 0) || (segedNowPath->size != 0))
    {
        while (segedNowPath->size != 0)
        {
            char *str = stackPop(segedNowPath);
            strcat(path, str);
            strcat(path, "/");
        }
        while (segedToPath->size != 0)
        {
            char *str = stackPop(segedToPath);
            strcat(path, str);
            strcat(path, "/");
        }
    }

    // sprintf(tmp, "%s/%s", nowPath, toPatcdh);
    // printf("%s\n", tmp);
    memset(nowPath, 0, sizeof(nowPath));
    strcpy(nowPath, path);
    printf("now real path = %s\n", nowPath);

    return 0;
}